package Servlet;

import dao.MyConnection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class addPlaceTimeServlet extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-cache");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String placeNumber = request.getParameter("placeNumber");
        String placeDate = request.getParameter("placeDate");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        int res = -1;

        if (placeDate == null || placeNumber == null || startTime == null || endTime == null) {
            res = -1;
        } else if (endTime.compareTo(startTime) <= 0) {
            res = -1;
        } else {
            MyConnection myCon = new MyConnection();
            myCon.getConnection();
            try {

                PreparedStatement ps = myCon.connection.prepareStatement("select count(*) from placetime where placeDate=? and PlaceNumber=? and ((?>=PlaceStartTime and  ?<=PlaceEndTime) or ( ?>=PlaceStartTime and ?<=PlaceEndTime) or(?<=PlaceStartTime and ?>=PlaceEndTime));");
                ps.setString(1, placeDate);
                ps.setString(2, placeNumber);
                ps.setString(3, startTime);
                ps.setString(4, startTime);
                ps.setString(5, endTime);
                ps.setString(6, endTime);
                ps.setString(7, startTime);
                ps.setString(8, endTime);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    if (rs.getInt(1) == 0) {
                        ps = myCon.connection.prepareStatement("insert into placetime values(null,?,?,?,?,1)");
                        ps.setString(1, placeNumber);
                        ps.setString(2, placeDate);
                        ps.setString(3, startTime);
                        ps.setString(4, endTime);
                        res = ps.executeUpdate();
                    }
                }
                ps.close();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                myCon.closeConnection();
            }
        }

        out.print(res);
    }
}
